#! /usr/bin/env python2
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2019 crane <crane@gosun>
#
# Distributed under terms of the MIT license.

"""

"""

import random
import math
import functools
# import numpy


pi  = math.pi
pi2 = math.pi * 2


def random_circle_point(radius=1):
    # 随机获取圆上一点
    angle = random.uniform(0, pi2)
    # y = math.sqrt(radius**2 - x*x)
    return angle

def n_circle_point(n):
    # 随机获取n个圆上的点
    l = []
    for i in range(n):
       l.append(random_circle_point())

    return l

def minus_to_int(n1, n2):
    # cmp返回值必须是int, 这里把相减后的值转换为int
    if n1 - n2 > 0:
        return 1
    if n1 - n2 < 0:
        return -1
    return 0

def point_cmp_from_0(angle1, angle2):
    # 圆上的点顺时针比较: 从first quadrant开始, 到forth quadrant结束
    return minus_to_int(angle1, angle2)

def point_cmp_from_180(angle1, angle2):
    # 从第3象限开始
    if angle1 > pi and angle2 < pi:
        return -1

    if angle1 < pi and angle2 > pi:
        return 1

    return minus_to_int(angle1, angle2)

def get_angle_base_negative(angle):
    if angle > pi:
        return angle - pi2      # 使用负值
    else:
        return angle

def in_half_circle(a1, a2):
    return a2 - a1 < math.pi

def one_pariment(num):
    # 一次试验
    points = n_circle_point(num)
    # clockwise_points = sorted(points, cmp=point_cmp_from_0)
    # # print(clockwise_points)
    # angle1 = clockwise_points[0]
    # angle2 = clockwise_points[-1]
    angle1 = min(points, key=functools.cmp_to_key(point_cmp_from_0))
    angle2 = max(points, key=functools.cmp_to_key(point_cmp_from_0))

    if in_half_circle(angle1, angle2):
        return True

    # clockwise_points = sorted(points, cmp=point_cmp_from_180)
    # print(clockwise_points)
    angle1 = min(points, key=functools.cmp_to_key(point_cmp_from_180))
    angle2 = max(points, key=functools.cmp_to_key(point_cmp_from_180))
    angle1 = get_angle_base_negative(angle1)
    angle2 = get_angle_base_negative(angle2)
    # print(angle1, angle2)
    return in_half_circle(angle1, angle2)

def four_point():
    cnt = 100000 * 10
    hit = 0
    num = 5
    for i in range(cnt):
        # if one_pariment(3):   # (1 + 2) / (2 ** 2)
        # if one_pariment(4):   # (1 + 3) / (2 ** 3)
        if one_pariment(num):     # (1 + 4) / (2 ** 4)
            hit += 1

    print("hit:", hit)
    proba = hit / float(cnt)
    print("probability:", proba)

    m1 = num - 1
    theory_proba = (1 + m1) / float(2**m1)
    print("theory  :", theory_proba)

    print("error  :", abs(proba - theory_proba) / theory_proba)


def main():
    print("start main")
    # test()
    four_point()

if __name__ == "__main__":
    main()
